package org.myhomework.servelet;

import org.myhomework.constant.Constants;
import org.myhomework.dao.UserDao;
import org.myhomework.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class AdminResetPasswordServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!checkPermission(req, resp)) {
            return;
        }
        String id = req.getParameter("id");
        String back = req.getParameter("back");
        if (null == id) {
            id = String.valueOf(req.getSession().getAttribute(Constants.USER_ID_ATTRIBUTE));
        }
        req.setAttribute("id", id);
        req.setAttribute("back", back);
        req.getRequestDispatcher("/admin-reset-pwd.jsp").forward(req, resp);
    }
    
    private boolean checkPermission(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = (Integer) req.getSession().getAttribute(Constants.USER_ID_ATTRIBUTE);
        User user = UserDao.getById(userId);
        if (Constants.ADMIN_TYPE != user.getType()) {
            resp.getWriter().write("无权访问");
            return false;
        }
        return true;
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!checkPermission(req, resp)) {
            return;
        }
        String id = req.getParameter("id");
        String _new = req.getParameter("new");
        String back = req.getParameter("back");
        String msg = "修改成功";
        UserDao.changePwd(Integer.valueOf(id), _new);
        req.setAttribute("msg", msg);
        req.setAttribute("back", back);
        req.getRequestDispatcher("/ok.jsp").forward(req, resp);
    }
}
